<template>
    <div>
        <el-button type="primary">导入</el-button>
        <el-button type="success" @click="batchInsertData">批量添加</el-button>
        <input type="file" accept=".xls,.xlsx" class="upload-file" @change="changeExcel($event)" />
        <el-table :data="userList" border style="width: 100%">
            <el-table-column type="index" :index="indexMethod" width="60" label="编号" align="center" />
            <el-table-column prop="loginName" label="用户名" width="120px" align="center" />
            <el-table-column prop="roleNames" label="角色名称" width="125px" align="center" />
            <el-table-column prop="userGender" label="性别" width="60px" align="center">
                <template #default="scope">
                    {{ scope.row.userGender ? "男" : "女" }}
                </template>
            </el-table-column>
            <el-table-column prop="userProvince" label="所在省" width="160px" align="center">
                <!-- 使用element-china-area-data 数据回显 -->
                <template #default="scope">
                    {{ codeToText[scope.row.userProvince] }}
                </template>
            </el-table-column>
            <el-table-column prop="userCity" label="所在市" width="100px" align="center">
                <template #default="scope">
                    {{ codeToText[scope.row.userCity] }}
                </template>
            </el-table-column>
            <el-table-column prop="userArea" label="所在县" width="160px" align="center">
                <template #default="scope">
                    {{ codeToText[scope.row.userArea] }}
                </template>
            </el-table-column>
            <el-table-column prop="fullAddress" label="详细地址" width="120px" align="center">
                <template #default="scope">
                    <el-tooltip v-if="scope.row.fullAddress.length > 5" class="box-item" effect="light"
                        :content="scope.row.fullAddress" placement="top-start">
                        <span>{{ scope.row.fullAddress.substring(0, 5) + '...' }}</span>
                    </el-tooltip>
                    <span v-else>{{ scope.row.fullAddress }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="createPerson" label="创建人" width="80px" align="center" />
            <el-table-column prop="createDate" label="创建日期" width="160px" align="center">
                <template #default="scope">
                    {{ scope.row.createDate.substring(0, 19).split("T")[0] + " " + scope.row.createDate.substring(0,
                        19).split("T")[1] }}
                </template>
            </el-table-column>
            <el-table-column prop="revisePerson" label="修改人" align="center" />
            <el-table-column prop="reviseDate" label="修改日期" width="160px" align="center">
                <template #default="scope">
                    {{ scope.row.reviseDate ? scope.row.reviseDate.substring(0, 19).split("T")[0] + " "
                        + scope.row.reviseDate.substring(0, 19).split("T")[1] : "" }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="110px" fixed="right" align="center">
                <template #default="scope">
                    <el-link @click="updateUserInfo(scope.row.userId)">修改</el-link>
                    &ensp;|&ensp;
                    <el-link @click="logicDelete(scope.row.userId)">删除</el-link>
                </template>
            </el-table-column>
        </el-table>
        <table style="margin: 10px auto;">
            <tr>
                <td>
                    <el-pagination v-model:current-page="page.index" v-model:page-size="page.size"
                        :page-sizes="[15, 20, 25]" layout="slot, sizes" :total="page.totalCount"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                        共 {{ page.totalCount }} 条，共 {{ page.pageCount }} 页，当前 {{ page.index }} / {{ page.pageCount }} 页
                    </el-pagination>
                </td>
                <td>
                    <el-pagination v-model:current-page="page.index" v-model:page-size="page.size"
                        :page-sizes="[15, 20, 25]" layout="slot, prev, pager, next" :total="page.totalCount"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页"
                        next-text="下一页">
                        <el-button :disabled="page.index == 1" @click="handleCurrentChange(1)">首页</el-button>
                    </el-pagination>
                </td>
                <td>
                    <el-pagination v-model:current-page="page.index" v-model:page-size="page.size"
                        :page-sizes="[15, 20, 25]" layout="slot, jumper" :total="page.totalCount"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                        <el-button :disabled="page.index == page.pageCount"
                            @click="handleCurrentChange(page.pageCount)">尾页</el-button>
                    </el-pagination>
                </td>
            </tr>
        </table>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, inject } from 'vue'
import { ElMenu, ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import * as XLSX from 'xlsx'
import { codeToText } from "element-china-area-data"


import http from '@/http'
const router = useRouter()

const page = reactive({
    size: 15,
    index: 1,
    totalCount: 0,
    pageCount: 0
})

interface IUserInfo {
    userId: number,
    userGender: boolean,
    loginName: string,
    passWord: string,
    userProvince: string,
    userCity: string,
    userArea: string,
    createPerson: string,
    createDate: string,
    revisePerson: string,
    reviseDate: string,
    isDelete: boolean
}
const userList = ref<IUserInfo[]>([])

const getUserList = () => {
    http.get("/api/User/GetUserInfoList", {
        params: {
            size: page.size,
            index: page.index
        }
    }).then(res => {
        userList.value = res.data.datas;
        page.totalCount = res.data.totalCount;
        page.pageCount = res.data.pageCount;
    })
}

const handleSizeChange = (val: number) => {
    page.size = val;
    getUserList();
}
const handleCurrentChange = (val: number) => {
    page.index = val;
    getUserList();
}

const updateUserInfo = (userId: number) => {
    router.push('/userUpdateInfo?userId=' + userId);
}

const logicDelete = (userId: number) => {
    ElMessageBox.confirm(
        '确定要删除吗？',
        '提示信息',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error',
        }
    )
        .then(() => {
            http.put("/api/User/LogicDelete?userId=" + userId).then(res => {
                if (res.data > 0) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                        duration: 500
                    });
                    getUserList();
                }
                else {
                    ElMessage({
                        type: 'error',
                        message: '删除失败',
                        duration: 500
                    })
                }
            })
        })
}

const indexMethod = (index: number) => {
    return index += (page.size) * (page.index - 1) + 1;
}



// 导入
const tableData = ref<unknown[]>([])
const changeExcel = (e: any) => {
    const files = e.target.files;
    if (files.length <= 0) {
        return false;
    }
    else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        console.log('上传格式不正确，请上传xls或者xlsx格式');
        return false;
    }
    // 读取表格
    const fileReader = new FileReader()
    fileReader.onload = ev => {
        console.log(ev.target)
        const workbook = XLSX.read(ev.target ? ev.target.result : null, {
            type: "binary"
        })
        const wsname = workbook.SheetNames[0]
        const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])
        console.log('ws:', ws) // 转换成json的数据
        dealExcel(ws)// 对数据进行自己需要的操作
        // tableData.value = ws
    }
    fileReader.readAsBinaryString(files[0])
}

function dealExcel(ws: any) {
    let keymap = {  // 我们要转换的开头
        "用户名": 'loginName',
        "密码": 'passWord',
        "性别": 'userGender',
        "所在省": 'userProvince',
        "所在市": 'userCity',
        "所在县": 'userArea',
        "详细地址": 'fullAddress',
        "部门": 'departmentId',
        /* 创建人: 'createPerson',
        创建日期: 'createDate',
        修改人: 'RevisePerson',
        修改日期: 'ReviseDate' */
    }
    ws.forEach((sourceObj: { [x: string]: any }) => {
        Object.keys(sourceObj).map(keys => {
            let newKey = keymap[keys]
            if (newKey) {
                sourceObj[newKey] = sourceObj[keys]
                delete sourceObj[keys]
            }
        })
    })
    tableData.value = ws
    console.log(tableData.value)
}

const batchInsertData = () => {
    http.post("/api/User/BatchInsertData", tableData.value).then(res => {
        if (res.data > 0) {
            ElMessage({
                type: 'success',
                message: '添加成功',
                duration: 1000
            });
            getUserList();
        }
        else {
            ElMessage({
                type: 'error',
                message: '添加失败',
                duration: 1000
            })
        }
    })
}

onMounted(() => {
    getUserList();
})
</script>

<style scoped></style>